import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Test {
    private static JFrame frame;
    private Map<String, String> buttonMap;

    public static void main(String[] args) {


        dynamicButtonsGUI();

    }

    public static void dynamicButtonsGUI() {
        String result2 = "";
//        String result2 = HttpRequest.get(url)
//                .header(Header.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0")
//                .header(Header.ACCEPT,"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/png,image/svg+xml,*/*;q=0.8")
//                .header(Header.ACCEPT_LANGUAGE,"zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
//                .header("Priority","u=0, i")
//                .timeout(20000)
//                .execute()
//                .body();
//        Console.log(result2);
        InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("code.txt");
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            String longString = stringBuilder.toString().trim(); // 去掉最后一行的换行符
            result2 = longString;

        } catch (IOException e) {
            e.printStackTrace();
        }
        // 创建一个正则表达式模式来匹配 data-sequence 和 title 属性
        Pattern pattern = Pattern.compile("data-sequence=\"(.*?)\".*?title='(.*?)'>", Pattern.DOTALL);
        // 创建一个 Matcher 对象来匹配 HTML 字符串
        Matcher matcher = pattern.matcher(result2);
        // 创建一个 Map 来存储提取的键值对
        Map<String, String> buttonMap = new HashMap<>();
        // 遍历所有匹配的结果
        while (matcher.find()) {
            String key = matcher.group(1); // data-sequence 的值
            String value = matcher.group(2); // title 的值，去掉两侧的单引号
            buttonMap.put(key, value);
        }
        // 打印 Map 集合中的键值对
//        for (Map.Entry<String, String> entry : resultMap.entrySet()) {
//            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
//        }
        //获取激活码
        int startIndex = result2.indexOf("let jbKeys = ") + "let jbKeys = ".length();
        String substring = result2.substring(startIndex);
        int startIndex1 = substring.indexOf(";");
        String jihuooma = substring.substring(0, startIndex1);

        String jsonPrettyStr = JSONUtil.toJsonStr(jihuooma);

        JSONObject jsonObject = JSONObject.parseObject(jsonPrettyStr);
        HashMap<String, String> objectObjectHashMap = new HashMap<>();
        for (Map.Entry<String, String> entry : buttonMap.entrySet()) {

            Object o = jsonObject.get(entry.getKey());
            JSONObject jsonObject1 = JSONObject.parseObject(o.toString());
            for (String s : jsonObject1.keySet()) {
                //激活码
                String o1 = (String) jsonObject1.get(s);
                String value = entry.getValue();
                objectObjectHashMap.put(value, o1);
            }


        }
        // 创建 JFrame
        frame = new JFrame("lzx破解");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());

        // 创建按钮并添加到 JFrame
        for (final String key : objectObjectHashMap.keySet()) {
            JButton button = new JButton("点击复制" + key + "激活码");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // 复制对应的 value 到剪贴板
                    String valueToCopy = objectObjectHashMap.get(key);
                    copyToClipboard(valueToCopy);
                    // 可以提示用户已复制
                    JOptionPane.showMessageDialog(frame, key + "激活码已经复制到剪贴板了 请在软件里填写激活！");
                }
            });
//            if ("IntelliJ IDEA".equals(key)|| "PhpStorm".equals(key)
//                    || "PyCharm".equals(key)|| "DataGrip".equals(key)
//                    || "Rainbow Brackets".equals(key)|| "WebStorm".equals(key)|| "MyBatis Log".equals(key)
//                    || "Elasticsearch".equals(key)|| "Redis Manager".equals(key)|| "PyCharm".equals(key)
//                    || "Database Tool".equals(key)|| "Kafka Client".equals(key) || "MyBatisCodeHelperPro (Marketplace Edition)".equals(key)
//            )
            if ("IntelliJ IDEA".equals(key) || "PhpStorm".equals(key)
                    || "PyCharm".equals(key)
                    || "Rainbow Brackets".equals(key) || "WebStorm".equals(key)
                    || "Database Tool".equals(key) || "MyBatisCodeHelperPro (Marketplace Edition)".equals(key)
            ) {
                frame.add(button);
            }
        }
// 创建一个新的按钮，用于复制文件夹
        JButton copyFolderButton = new JButton("先点这个破解 再点复制激活码！");
        copyFolderButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
//                String fileURL = "https://hardbin.com/ipfs/bafybeiawsvnhqx5o2aqa37pvq7brlk7vqj2cpty3b5xac655bxbpqbpkq4/files/jetbra-ded4f9dc4fcb60294b21669dafa90330f2713ce4.zip";
//                try {
//                    downloadFile(fileURL, saveDir);
//                } catch (IOException ex) {
//                    throw new RuntimeException(ex);
//                }
                String saveDir = "C:/jetbra1/jetbra.zip";
                File outputFile = new File(saveDir);
                if (!outputFile.getParentFile().exists()) {
                    outputFile.getParentFile().mkdirs(); // 创建父目录
                }
                try {
                    unzipFile(saveDir);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                System.out.println("下载并解压完成");
                String scriptPath = "C:\\jetbra1\\jetbra\\scripts\\install-all-users.vbs";
                // 执行VBS脚本
                ProcessBuilder processBuilder = new ProcessBuilder("wscript", scriptPath);
                try {
                    Process process = processBuilder.start();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }

            }
        });

        // 将新按钮添加到 JFrame
        frame.add(copyFolderButton);

        // 设置窗口大小并显示
        frame.setSize(500, 250);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null); // 居中显示
        // 设置窗口不可调整大小
        frame.setResizable(false);
    }

    public static void downloadFile(String fileURL, String saveDir) throws IOException {
        URL url = new URL(fileURL);
        File outputFile = new File(saveDir);
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs(); // 创建父目录
        }
        try (InputStream in = url.openStream()) {
            FileOutputStream fileOutputStream = new FileOutputStream(saveDir);

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }
            fileOutputStream.close();
        }
    }

    public static void unzipFile(String zipFilePath) throws IOException {
        File zipFile = new File(zipFilePath);
        String projectRoot = System.getProperty("user.dir");
        // 构建文件路径
        String destDir = projectRoot + "/src/jetbra.zip";
        File destDirectory = new File(destDir);
        if (!destDirectory.exists()) {
            destDirectory.mkdirs(); // 创建目标目录
        }
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry = zipIn.getNextEntry();
        // Iterates over entries in the zip file
        while (entry != null) {
            String filePath = destDir + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                // If the entry is a file, extracts it
                extractFile(zipIn, filePath);
            } else {
                // If the entry is a directory, make the directory
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();
    }

    private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] bytesIn = new byte[4096];
        int read;
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
        }
        bos.close();
    }

    public static void copyResourcesFromJar(String folderPathInJar, String targetFolderPath) throws Exception {
        // 获取当前类所在的JAR文件
        JarFile jarFile = new JarFile(Test.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        // 获取JAR文件条目的枚举器
        java.util.Enumeration<JarEntry> entries = jarFile.entries();

        // 创建目标文件夹
        File targetDir = new File(targetFolderPath);
        targetDir.mkdirs();

        // 遍历所有条目
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String entryName = entry.getName();

            // 如果条目名称以指定的文件夹路径开始，则复制它
            if (entryName.startsWith(folderPathInJar)) {
                // 计算相对路径
                String relativePath = entryName.substring(folderPathInJar.length());
                File targetFile = new File(targetDir, relativePath);

                // 如果条目是目录，则创建目录
                if (entry.isDirectory()) {
                    targetFile.mkdirs();
                } else {
                    // 如果条目是文件，则复制文件
                    copyFile(jarFile.getInputStream(entry), targetFile);
                }
            }
        }
        jarFile.close();
    }

    private static void copyFile(InputStream in, File targetFile) throws Exception {
        // 确保目标文件所在的目录存在
        targetFile.getParentFile().mkdirs();

        // 创建文件输出流
        FileOutputStream out = new FileOutputStream(targetFile);
        try {
            byte[] buffer = new byte[1024];
            int length;
            // 读取并写入文件内容
            while ((length = in.read(buffer)) != -1) {
                out.write(buffer, 0, length);
            }
        } finally {
            // 关闭输入和输出流
            in.close();
            out.close();
        }
    }

    // 添加一个方法来复制文件夹
    private static void copyDirectory(File sourceDir, File targetDir) throws IOException {
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }

        // 获取源文件夹下的所有文件和文件夹
        File[] files = sourceDir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    // 递归复制子文件夹
                    copyDirectory(file, new File(targetDir, file.getName()));
                } else {
                    // 复制文件
                    Files.copy(file.toPath(), new File(targetDir, file.getName()).toPath(), StandardCopyOption.REPLACE_EXISTING);
                }
            }
        }
    }

    private static void copyToClipboard(String text) {
        // 获取系统剪贴板
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        // 创建一个字符串剪辑板内容
        StringSelection selection = new StringSelection(text);
        // 将剪辑板内容设置为剪贴板内容
        clipboard.setContents(selection, selection);
    }

}
